<template>
  <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关的参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert
      >、
      <!-- 选择商品分类 -->
      <el-row class="catelist">
        <el-col :span="10">
          <span>商品分类：</span>
          <el-cascader
            v-model="selectId"
            :options="cateList"
            :props="cateprops"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--     动态参数表格 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isThird"
            @click="addDynamic"
          >
            添加参数
          </el-button>
          <el-table :data="manyList" border style="width: 100%">
            <el-table-column type="expand" width="50">
              <template v-slot="scope">
                <!-- 循环标签 -->
                <el-tag
                  closable
                  @close="handleClose(scope.row, index)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}
                </el-tag>
                <!-- 生成标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <!-- 编辑 -->

                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editInfo(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!--  删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="isDelete(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--   静态属性表格 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isThird"
            @click="addDynamic"
          >
            添加属性
          </el-button>
          <el-table :data="onlyList" border style="width: 100%">
            <el-table-column type="expand" width="50">
              <template v-slot="scope">
                <!-- 循环标签 -->
                <el-tag
                  closable
                  @close="handleClose(scope.row, index)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}
                </el-tag>
                <!-- 生成标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <!-- 编辑 -->

                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editInfo(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!--  删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="isDelete(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加对话框功能 -->
      <el-dialog
        :title="'添加' + dynamicTitle"
        :visible.sync="showAdddialog"
        width="40%"
        @close="closeAdd"
      >
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="addRef"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item :label="dynamicTitle" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showAdddialog = false">取 消</el-button>
          <el-button type="primary" @click="commitAdd">确 定</el-button>
        </span>
      </el-dialog>
      <!--  编辑对话框 -->
      <el-dialog
        :title="'修改' + dynamicTitle"
        :visible.sync="showEditdialog"
        width="40%"
        @close="closeEdit"
      >
        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editRef"
          label-width="80px"
        >
          <el-form-item :label="dynamicTitle" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showEditdialog = false">取 消</el-button>
          <el-button type="primary" @click="commitEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除 -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      cateList: [],
      cateprops: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //级联选择框双向绑定的数组
      selectId: [],
      //默认被激活页签的名称
      activeName: "many",
      manyList: [],
      onlyList: [],
      showAdddialog: false,
      addForm: {
        attr_name: "",
      },
      addRules: {
        attr_name: [
          { required: true, message: "请输入参数名", trigger: "blur" },
        ],
      },
      showEditdialog: false,
      editForm: {},
      editRules: {
        attr_name: [
          { required: true, message: "请输入参数名", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    //判断是否为三级分类
    isThird() {
      if (this.selectId.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    //获取三级分类的id
    getCateId() {
      if (this.selectId.length !== 3) {
        return;
      }
      return this.selectId[this.selectId.length - 1];
    },
    //动态计算对话框的标题
    dynamicTitle() {
      if (this.activeName === "many") return "动态参数";
      else {
        return "静态属性";
      }
    },
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$request({
        url: "categories",
        params: {
          type: 3,
        },
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.cateList = res.data;
      //console.log(this.cateList);
    },
    //商品分类发生变化
    handleChange() {
      this.getParamsList();

      //console.log(this.selectId);
    },
    //参数列表
    async getParamsList() {
      //选择的不是三级分类
      if (this.selectId.length !== 3) {
        this.selectId = [];
        //如果不是三级应该清空动态静态表格
        this.manyList = [];
        this.onlyList = [];
        return;
      }
      //获取当前面板的参数
      //console.log(this.getCateId);
      const { data: res } = await this.$request({
        url: `categories/${this.getCateId}/attributes`,
        params: {
          sel: this.activeName,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        //控制每行的文本框的显示与隐藏
        //添加属性

        item.inputVisible = false;
        item.inputValue = "";
      });
      console.log(res.data);
      if (this.activeName == "many") {
        this.manyList = res.data;
      } else {
        this.onlyList = res.data;
      }
    },
    //点击tab切换
    handleTabClick() {
      this.getParamsList();
      console.log(this.activeName);
    },
    //显示添加动态的对话框
    addDynamic() {
      this.showAdddialog = true;
    },
    closeAdd() {
      this.$refs.addRef.resetFields();
    },
    //确定添加
    commitAdd() {
      //确定添加前先预校验
      this.$refs.addRef.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$request({
            url: `categories/${this.getCateId}/attributes`,
            method: "post",
            data: {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            },
          });
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          }
          console.log(res);
          this.$message.success(res.meta.msg);
          this.getParamsList();
          this.showAdddialog = false;
        }
      });
    },

    //根据 ID 查询参数
    async getParamsInfo(id) {
      const { data: res } = await this.$request({
        url: `categories/${this.getCateId}/attributes/${id}`,
        params: {
          attr_sel: this.activeName,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.editForm = res.data;
    },
    //编辑框
    editInfo(id) {
      this.getParamsInfo(id);
      this.showEditdialog = true;
    },

    commitEdit() {
      this.$refs.editRef.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$request({
            url: `categories/${this.getCateId}}/attributes/${this.editForm.attr_id}`,
            method: "put",
            data: {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
            },
          });
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }
          this.$message.success(res.meta.msg);
          this.getParamsList();
          this.showEditdialog = false;
        }
      });
    },
    closeEdit() {
      this.$refs.editRef.resetFields();
    },
    async isDelete(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
      const { data: ress } = await this.$request({
        url: `categories/${this.getCateId}/attributes/${id}`,
        method: "delete",
      });
      if (ress.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.getParamsList();
      this.$message.success("删除成功");
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //增加标签
      row.attr_vals.push(row.inputValue);
      //将input重置为空
      row.inputValue = "";

      row.inputVisible = false;
      //将新标签保存到数据库
      this.saveData(row);
    },
    //将修改的参数标签保存到数据库
    async saveData(row) {
      const { data: res } = await this.$request({
        url: `categories/${this.getCateId}/attributes/${row.attr_id}`,
        method: "put",
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          //这是里数组，服务器只接受字符串
          attr_vals: row.attr_vals.join(","),
        },
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("更新参数成功");
    },
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动获取焦点
      //nextTick就是当页面上元素被重新渲染之后，才会回调
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleClose(row, i) {
      row.attr_vals.splice(i, 1);
      //保存到数据库
      this.saveData(row);
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 30px;
}
.el-cascader {
  width: 280px;
}
.catelist {
  margin-top: 30px;
}
.el-tag {
  margin: 5px 15px;
}
.input-new-tag {
  width: 20%;
}
</style>
